package vip.xiaonuo.client.modular.wxpay.util;

import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Base64;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * 钉钉通知工具类
 */
@Slf4j
public class DingTalkUtil {

    /**
     * 发送钉钉消息
     *
     * @param webhook 钉钉机器人webhook地址
     * @param secret  钉钉机器人密钥
     * @param content 消息内容
     * @param isAtAll 是否@所有人
     */
    public static void sendMessage(String webhook, String secret, String content, boolean isAtAll) {
        try {
            // 如果有密钥，需要计算签名
            if (secret != null && !secret.isEmpty()) {
                long timestamp = System.currentTimeMillis();
                String stringToSign = timestamp + "\n" + secret;
                Mac mac = Mac.getInstance("HmacSHA256");
                mac.init(new SecretKeySpec(secret.getBytes(StandardCharsets.UTF_8), "HmacSHA256"));
                byte[] signData = mac.doFinal(stringToSign.getBytes(StandardCharsets.UTF_8));
                String sign = URLEncoder.encode(new String(Base64.encodeBase64(signData)), "UTF-8");
                webhook = webhook + "&timestamp=" + timestamp + "&sign=" + sign;
            }

            // 构建消息体
            Map<String, Object> messageMap = new HashMap<>(8);
            messageMap.put("msgtype", "text");
            
            Map<String, Object> text = new HashMap<>(2);
            text.put("content", content);
            messageMap.put("text", text);
            
            Map<String, Object> at = new HashMap<>(2);
            at.put("isAtAll", isAtAll);
            messageMap.put("at", at);
            
            String result = HttpUtil.post(webhook, JSONUtil.toJsonStr(messageMap));
            JSONObject resultJson = JSONUtil.parseObj(result);
            
            if (Objects.equals(0, resultJson.getInt("errcode"))) {
                log.info("钉钉消息发送成功: {}", content);
            } else {
                log.error("钉钉消息发送失败: {}, 错误: {}", content, result);
            }
        } catch (Exception e) {
            log.error("钉钉消息发送异常", e);
        }
    }
} 